import React, {Component} from "react";
import PostItem from "./PostItem";

class PostList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            posts: [],
        };
        this.timer = null;
        //this.handleVote = this.handleVote.bind(this);
    }

    componentDidMount() {
        this.timer = window.setTimeout(() => {
            this.setState({
                posts: [
                    {"id": 1, "author": "张三", "date": "2019-11-25", "vote": 1},
                    {"id": 2, "author": "李四", "date": "2019-11-24", "vote": 0},
                    {"id": 3, "author": "王五", "date": "2019-11-24", "vote": 5},
                ]
            })
        }, 1000);
    }

    componentWillUnmount() {
        if (this.timer) {
            window.clearTimeout(this.timer);
        }
    }

    handleVote = (id) => {
        const posts = this.state.posts.map(item => {
            if (item.id === id) {
                return {...item, vote: ++item.vote};
            } else {
                return {...item};
            }
        });
        this.setState({
            posts: posts,
        })
    }

    render() {
        return (
            <div>
                帖子列表:
                <ul>
                    {this.state.posts.map(item => (
                        <PostItem post={item} onVote={this.handleVote} key={item.id}/>
                    ))}
                </ul>
            </div>
        );
    }
}

export default PostList;

